package com.gao.musicApi.service.impl;

import com.gao.musicApi.model.SearchModel;
import com.gao.musicApi.model.Song;
import com.gao.musicApi.model.migu.Response;
import com.gao.musicApi.model.migu.Result;
import com.gao.musicApi.service.MusicApi;
import com.gao.musicApi.util.GsonUtil;
import org.jsoup.Jsoup;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MiguApi implements MusicApi {
    private String searchUrl = "http://pd.musicapp.migu.cn/MIGUM3.0/v1.0/content/search_all.do?&ua=Android_migu&version=5.0.1&text=%s&pageNo=%s&pageSize=10&searchSwitch={\"song\":1,\"album\":0,\"singer\":0,\"tagSong\":0,\"mvSong\":0,\"songlist\":0,\"bestShow\":1}";

    public List<Song> search(SearchModel m) {
        String url = String.format(searchUrl, m.getKw(), m.getPage());
        List<Song> result = new ArrayList<>();
        try {
            String r = Jsoup.connect(url).ignoreContentType(true).get().text();
            Response res = GsonUtil.GsonToBean(r, Response.class);
            List<Result> datas = res.getSongResultData().getResult();
            for (Result data : datas) {
                Song s = new Song();
                s.setName(data.getName());
                s.setSinger(data.getSingers() == null ? null : data.getSingers().get(0).getName());
                s.setImgItems(data.getImgItems() == null ? null : data.getImgItems().get(0).getImg());
                s.setLyricUrl(data.getLyricUrl());
                s.setAlbums(data.getAlbums() == null ? null : data.getAlbums().get(0).getName());
                s.setSongUrl(data.getContentId());
                result.add(s);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public String getUrl(Song song) {
        String url = "http://app.pd.nf.migu.cn/MIGUM2.0/v1.0/content/sub/listenSong.do?toneFlag=SQ&netType=00&userId=15548614588710179085069&ua=Android_migu&version=5.1&copyrightId=0&contentId=$s&resourceType=E&channel=0";
//        try {
//            String r = Jsoup.connect(url).ignoreContentType(true).get().head().text();
//            System.out.println(r);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        return String.format(url, song.getSongUrl());
    }
}
